package com.ganlebao.study.springcloudfeignclient.basic.feignconfig;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.Request;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Iterator;

@Component
public class LogRequestInterceptor implements RequestInterceptor {
    public static final Logger logger = LoggerFactory.getLogger(LogRequestInterceptor.class);
    @Autowired
    private ObjectMapper om;
    @Value("${springQueryMap.use.flag:false}")
    private Boolean springQueryMapFlag;

    @Override
    public void apply(RequestTemplate template) {
        String url = template.url();
        //默认对方接口参数是User,但是feign将对象转为json并发送了.服务端接口无法识别,拦截器转化为其他接口
        if (url.endsWith("echo-user") && !springQueryMapFlag) {
            Request.Body body = template.requestBody();
            try {
                JsonNode node = om.readTree(body.asString());
                Iterator<String> itor = node.fieldNames();
                while (itor.hasNext()) {
                    String fieldName = itor.next();
                    template.query(fieldName, node.findValue(fieldName).asText(""));
                }
            } catch (IOException e) {
                logger.error("server/test/echo-user 解析json参数失败", e);
            }
        }
    }
}
